package com.gopay.common.security.validcode.manager.impl;

import java.util.Date;

import javax.annotation.Resource;

import com.gopay.common.cipher.utils.SensitiveInfoUtils;
import org.apache.commons.lang3.StringUtils;

import com.gopay.common.constants.validcode.CodeType;
import com.gopay.common.domain.vs.VsValidCodeDtl;
import com.gopay.common.security.validcode.dao.ValidCodeDAO;
import com.gopay.common.security.validcode.manager.ValidCodeManager;
import com.gopay.common.util.DateUtils;

/**
 * 
 * @AbstractValidCode.java
 * @author yaobo
 * @2013-5-17 上午10:07:02 www.gopay.com.cn Inc.All rights reserved.
 */
public abstract class AbstractValidCode implements ValidCodeManager {
    /**
     * 验证过期时间(秒)，默认为30分钟
     */
    protected int expirTime = 1800;

    @Resource(name = "validCodeDAO")
    private ValidCodeDAO validCodeDAO;

    /**
     * 生成验证码逻辑方法，由子类实现不同验证码业务需求
     * 
     * @param type
     * @param voID
     * @return
     */
    protected abstract VsValidCodeDtl generateCode(CodeType type, String voID);

    /**
     * 生产验证码前业务逻辑
     * 
     * @param type
     * @param voID
     */
    protected void generateBefor(CodeType type, String voID) {
        // 生成验证码前先删除掉原有验证码
        validCodeDAO.delete(type, voID);
    }

    @Override
    public VsValidCodeDtl generate(CodeType type, String voID) {
        //generateBefor(type, voID);

        VsValidCodeDtl code = generateCode(type, voID);
        //生产bug8期 lx 2017-8-11 15:36:07 验证码加密存储
        code.setCode(SensitiveInfoUtils.smartEncryptWithCheck(code.getCode()));
        code = validCodeDAO.save(code);

        return code;
    }
    

    @Override
    public boolean valid(CodeType type, String voID, String code) {
        boolean flag = false;
        VsValidCodeDtl validCode = validCodeDAO.getValidCode(type, voID);
        if (validCode == null) {
            return false;
        }

        // 当前时间
        Date currentDate = DateUtils.getSystemDate();
        long curDate = currentDate.getTime();
        long dbDate = validCode.getCreated().getTime();

        long curr = (curDate - dbDate);
        long expir = expirTime * 1000;

        // 验证码是否过期 AND 验证码是否匹配(忽略大小写)
        //if (curr <= expir && StringUtils.equalsIgnoreCase(code, validCode.getCode())) {
        //生产bug8期 lx 2017-8-11 15:36:07 验证码加密存储
        if (curr <= expir && StringUtils.equalsIgnoreCase(code, SensitiveInfoUtils.smartDecryptWithCheck(validCode.getCode()))) {
            flag = true;
        }

        // 更新修改时间，以证明验证过
        validCode.setModified(currentDate);
        validCodeDAO.update(validCode);

        return flag;
    }

}
